package ksj.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;

public class Utility {

	public static int classCounter = 0;

	static HSSFRow rowxls;
	static XSSFRow rowxlsx;
	private static List<Integer> rowList = null;
	private static boolean enough = false;
	private static String newFileName = "";
	private static Row currentRow = null;
	private static int endingRow = 0;

	public static String DATA_STORE = "";

	private static final String AB = "123456789abcdefghijklmnpqrstuvwxyz";
	private static Random rnd = new Random();

	public static String validationResultInnerHTML = "";
	private static String formattingString;
	private static DecimalFormat formatter;
	private static FieldPosition fPosition;
	private static StringBuffer buffer;

	public static String randomString(int len) {
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(AB.charAt(rnd.nextInt(AB.length())));
		return sb.toString();
	}

	public static void configureLog() {
		BasicConfigurator.configure(); // basic log4j configuration
		org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO);
	}

	public static String getOSName() {
		String OPERATING_SYSTEM = System.getProperty("os.name").toLowerCase();
		return OPERATING_SYSTEM;
	}

	public static boolean containsArray(String[] array, String item) {
		try {
			for (int i = 0; i < array.length; i++) {
				if (array[i].equals(item)) {
					return true;
				}
			}
		} catch (Exception ex) {

		}
		return false;
	}

	/**
	 * Method for checking exact word containment
	 * 
	 * @param source
	 * @param subItem
	 * @return
	 */
	public static boolean contains(String source, String subItem) {
		String pattern = "\\b" + subItem + "\\b";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(source);
		return m.find();
	}

	public static Date getFirstDayofLastMonth(String format) {
		return DateUtil.getFirstDayofLastMonth(format);
	}
	
	public static Date getFirstDayofCurrentMonth(String format){
		return DateUtil.getFirstDayofCurrentMonth(format);
	}

	public static Date getLastDayofLastMonth(String format) {
		return DateUtil.getLastDayofLastMonth(format);
	}

	public static String getIPHostName() {
		InetAddress ip;
		String hostname = "";
		try {
			ip = InetAddress.getLocalHost();
			hostname = ip.getCanonicalHostName();
			// System.out.println("Your current Hostname/IP address : " +
			// hostname + "/" + ip);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return hostname;
	}

	@SuppressWarnings("unchecked")
	public static String getJobIdFromZipFile(String filePath, String fileName) {
		String jobId = "";
		ZipFile zip = null;
		try {
			zip = new ZipFile(filePath + fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
		if (entries.hasMoreElements()) {
			ZipEntry entry = entries.nextElement();
			String insideZipFileName = entry.getName();
			jobId = insideZipFileName.split("_")[1];
		}
		return jobId;
	}

	public static boolean contains(String[] array, String item) {
		try {
			for (int i = 0; i < array.length; i++) {
				if (array[i].equals(item)) {
					return true;
				}
			}
		} catch (Exception ex) {

		}
		return false;
	}

	public static int readFile(String path, String fileName, OutputStream os) {
		BufferedOutputStream output = null;
		FileInputStream fis = null;
		byte[] buffer = null;
		try {
			File file = new File(normalizePath(path + fileName));

			output = new BufferedOutputStream(os);
			buffer = new byte[(int) file.length()];
			fis = new FileInputStream(file);
			fis.read(buffer);
			output.write(buffer);

			return (int) file.length();
		} catch (IOException io) {
			System.err.println("FileUtility>ReadFile [Image]>> " + io.getCause());
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				fis.close();
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// IOUtils.closeQuietly(fis);
			// IOUtils.closeQuietly(output);
		}
		return 0;

	}

	public static String normalizePath(String path) {
		return path.replace("\\\\", "\\").replace("//", "/");
	}

	public static String getRandomString(int len) {
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(AB.charAt(rnd.nextInt(AB.length())));
		return sb.toString();
	}

	public static int CalculateAge(Long date) {
		Date birthDate = new Date(0);
		if (date != null)
			birthDate = new Date(date);
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		int birthYear = Integer.parseInt(format.format(birthDate));
		int currentYear = Integer.parseInt(format.format(new Date(System.currentTimeMillis())));
		int age = currentYear - birthYear;

		return age;
	}

	public static Time stringToTime(String time) {
		Time timeValue = null;
		try {
			DateFormat formatter = new SimpleDateFormat("HH:mm:ss");

			timeValue = new java.sql.Time(formatter.parse(time).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return timeValue;

	}

	public static Timestamp stringToTimeStamp(String time) {
		Timestamp timestamp = null;
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
			Date parsedDate = dateFormat.parse(time);
			timestamp = new java.sql.Timestamp(parsedDate.getTime());
		} catch (Exception e) { // this generic but you can control another
								// types of exception
			// look the origin of excption
		}
		return timestamp;

	}

	public static Date stringToDate(String startDateString) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date startDate = null;
		try {
			startDate = df.parse(startDateString);
			String newDateString = df.format(startDate);
			System.out.println(newDateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return startDate;
	}

	public static Date stringToDate(String startDateString, String format) {
		DateFormat df = new SimpleDateFormat(format);
		Date startDate = null;
		try {
			startDate = df.parse(startDateString);
			String newDateString = df.format(startDate);
			System.out.println(newDateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return startDate;
	}

	public static String dateToString(String format, Date date) {
		DateFormat df = new SimpleDateFormat(format);
		String dayString = df.format(date);
		return dayString;
	}

	public static String renameFile(String path, String fileName, String renameTo) throws Exception {
		String finalName = "";
		String OS = Utility.getOSName();
		try {
			String tempRealName = fileName;
			if (OS.contains("win")) {
				if (!path.endsWith("\\")) {
					path = path + "\\";
				}
			} else {
				if (!path.endsWith("/")) {
					path = path + "/";
				}
			}

			fileName = tempRealName.substring(0, tempRealName.lastIndexOf("."));
			String extension = tempRealName.substring(tempRealName.lastIndexOf("."), tempRealName.length());

			String tempFileName2 = renameTo;
			renameTo = tempFileName2.substring(0, tempFileName2.lastIndexOf("."));
			String extension2 = tempFileName2.substring(tempFileName2.lastIndexOf("."), tempFileName2.length());

			finalName = renameTo + extension;

			File actualFile = new File(path + tempRealName);
			File renamedFile = new File(path + finalName);

			// if (actualFile.renameTo(renamedFile)) {
			// //LOG.info(path + fileName + " move to: " + path + finalName + "
			// success!");
			// chagnePermission(renamedFile.getCanonicalPath());
			// } else {
			// //LOG.info(path + fileName + " move to: " + path + finalName + "
			// failed!");
			// }

			FileUtils.moveFile(actualFile, renamedFile);
			chagnePermission(renamedFile.getCanonicalPath());

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return finalName;
	}

	public static String moveFile(String sourcePath, String sourceFileName, String destinationPath,
			String destinationFileName) throws Exception {
		String finalName = "";
		String OS = Utility.getOSName();
		try {
			String tempRealName = sourceFileName;
			if (OS.contains("win")) {
				if (!sourcePath.endsWith("\\")) {
					sourcePath = sourcePath + "\\";
				}

				if (!destinationPath.endsWith("\\")) {
					destinationPath = destinationPath + "\\";
				}
			} else {
				if (!sourcePath.endsWith("/")) {
					sourcePath = sourcePath + "/";
				}

				if (!destinationPath.endsWith("/")) {
					destinationPath = destinationPath + "/";
				}
			}

			sourceFileName = tempRealName.substring(0, tempRealName.lastIndexOf("."));
			String extension = tempRealName.substring(tempRealName.lastIndexOf("."), tempRealName.length());

			String tempFileName2 = destinationFileName;
			destinationFileName = tempFileName2.substring(0, tempFileName2.lastIndexOf("."));
			String extension2 = tempFileName2.substring(tempFileName2.lastIndexOf("."), tempFileName2.length());

			finalName = destinationFileName + extension;

			File actualFile = new File(sourcePath + tempRealName);
			File renamedFile = new File(destinationPath + finalName);

			// if (actualFile.renameTo(renamedFile)) {
			// //LOG.info(sourcePath + sourceFileName + " move to: " +
			// sourcePath
			// + finalName + " success!");
			// chagnePermission(renamedFile.getCanonicalPath());
			// } else {
			// //LOG.info(sourcePath + sourceFileName + " move to: " +
			// sourcePath
			// + finalName + " failed!");
			// }
			FileUtils.moveFile(actualFile, renamedFile);
			chagnePermission(renamedFile.getCanonicalPath());

		} catch (Exception e) {
			// LOG.info(sourcePath + sourceFileName + " move to: " + sourcePath
			// + finalName + " failed!");
			e.printStackTrace();
			throw e;
		}
		return finalName;
	}

	public static void chagnePermission(String filePath) throws IOException {
		try {
			File file = new File(filePath);

			// set application user permissions to 777
			file.setExecutable(true);
			file.setReadable(true);
			file.setWritable(true);

			// change permission to 777 for all the users
			// no option for group and others
			file.setExecutable(true, false);
			file.setReadable(true, false);
			file.setWritable(true, false);

			// using PosixFilePermission to set file permissions 777
			Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
			// add owners permission
			perms.add(PosixFilePermission.OWNER_READ);
			perms.add(PosixFilePermission.OWNER_WRITE);
			perms.add(PosixFilePermission.OWNER_EXECUTE);
			// add group permissions
			perms.add(PosixFilePermission.GROUP_READ);
			perms.add(PosixFilePermission.GROUP_WRITE);
			perms.add(PosixFilePermission.GROUP_EXECUTE);
			// add others permissions
			perms.add(PosixFilePermission.OTHERS_READ);
			perms.add(PosixFilePermission.OTHERS_WRITE);
			perms.add(PosixFilePermission.OTHERS_EXECUTE);
			if (!Utility.getOSName().contains("win")) {

				Files.setPosixFilePermissions(Paths.get(filePath), perms);
			}
			// LOG.info("permissions changed for file: " + filePath);
		} catch (Exception e) {
			// LOG.info("Error while changing permissions of file: " +
			// filePath);
			// LOG.error("Error while changing permissions of file: " +
			// filePath, e.fillInStackTrace());
			e.printStackTrace();
		}
	}

	public static int getCurrentYear() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		return year;
	}

	public static int getCurrentMonth() {
		Calendar c = Calendar.getInstance();
		int month = c.get(Calendar.MONTH) + 1;
		return month;
	}

	public static String getMonthNameShort(int month) {
		String[] shortMonths = new DateFormatSymbols().getShortMonths();
		// for (String shortMonth : shortMonths) {
		// System.out.println("shortMonth = " + shortMonth);
		// }
		return shortMonths[month - 1];
	}

	public static String getMonthName(int month) {
		String[] months = new DateFormatSymbols().getMonths();
		// for (String bigMonth : months) {
		// System.out.println("month = " + bigMonth);
		// }
		return months[month - 1];
	}

	public static String formatFailedItemFileName(String oldFileName) {
		String finalName = "";
		String fileName = oldFileName.substring(0, oldFileName.lastIndexOf("."));
		String extension = oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());
		finalName = fileName + "." + "VF" + extension;
		return finalName;
	}

	public static String formatValidateFileName(String oldFileName) {
		String finalName = "";
		String fileName = oldFileName.substring(0, oldFileName.lastIndexOf("."));
		String extension = oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());
		finalName = fileName + "." + "validated" + extension;
		return finalName;
	}

	public static void createDirIfNotExist(String directory) {
		File file = new File(directory);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static boolean removeFromFile(String textFile, String fileDirectory, String signToRemove) {
		String fileName = textFile.substring(0, textFile.lastIndexOf("."));
		String fileExt = textFile.substring(textFile.lastIndexOf("."), textFile.length());
		FileWriter fileWriter = null;
		try {
			File fileToRead = new File(textFile);
			FileReader fileReader = new FileReader(fileToRead);
			BufferedReader br = new BufferedReader(fileReader);

			File fileToWrite = new File(fileName + "_2" + fileExt);
			fileWriter = new FileWriter(fileToWrite);
			String line;
			String tempLine = "";
			boolean compareLines = true;
			boolean firstLine = true;
			while ((line = br.readLine()) != null) {
				// process the line.

				if (!line.trim().equals("")) {

					if (firstLine) {
						firstLine = false;
						tempLine = line;
					}
					if (compareLines) {
						if (line.equals(tempLine)) {
							compareLines = false;
							fileWriter.write(line + "\r\n");
							line = br.readLine();
						}
					}
					if (!compareLines) {
						if (!textFile.contains("Hourly_Sales")) {
							if (line.contains(signToRemove)) {
								line = line.replace(signToRemove, "");
							}
							if (line.contains("(")) {
								line = line.replace("(", "-");
								line = line.replace(")", "");
							}
						}
						fileWriter.write(line + "\r\n");
					}
				}
			}
			fileWriter.flush();
			fileWriter.close();
			fileReader.close();
			br.close();

			if (fileToRead.exists()) {
				fileToRead.delete();
			}

			Utility.renameFile(fileDirectory, fileToWrite.getName(), fileToRead.getName());

			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				fileWriter.flush();
				fileWriter.close();
			} catch (IOException e) {
				// e.printStackTrace();
			}
		}

	}

	private static void readFromSpreadSheet_xls(String workBookName) throws Exception {
		rowList = new ArrayList<Integer>();
		try {
			enough = false;
			File file = new File(workBookName);
			FileInputStream fis = new FileInputStream(file);
			HSSFWorkbook workbook = new HSSFWorkbook(fis);
			HSSFSheet spreadsheet = workbook.getSheetAt(0);
			Iterator<Row> rowIterator = spreadsheet.iterator();
			while (rowIterator.hasNext()) {
				if (!enough) {
					rowxls = (HSSFRow) rowIterator.next();
					// Iterator<Cell> cellIterator = rowxlsx.cellIterator();
					Cell cell = rowxls.getCell(0);
					// Cell cell = cellIterator.next();

					switch (cell.getCellType()) {
					case Cell.CELL_TYPE_NUMERIC:
						System.out.print(cell.getNumericCellValue() + " \t\t ");
						break;
					case Cell.CELL_TYPE_BLANK:
						if (cell.getStringCellValue().equals("")) {
							rowList.add(rowxls.getRowNum());
						}
						break;
					case Cell.CELL_TYPE_STRING:
						// if (cell.getStringCellValue().contains("SIC Focus
						// Group")
						// || cell.getStringCellValue().contains("Member Type"))
						// {
						currentRow = rowxls;
						enough = true;
						// }
						break;
					}
					// System.out.println();
				} else {
					break;
				}
			}
			// LOG.info("rows to delete: " + rowList);
			// workbook.close();
			fis.close();
			if (fis != null) {
				fis = null;
				file = null;
			}

		} catch (Exception e) {
			// LOG.info("The downloaded file is old Excel version please update
			// the Excel version: " + workBookName);
			e.printStackTrace();
			throw e;
		}
	}

	private static void readFromSpreadSheet_xlsx(String workBookName) throws Exception {
		rowList = new ArrayList<Integer>();
		try {
			enough = false;
			File file = new File(workBookName);
			FileInputStream fis = new FileInputStream(file);
			XSSFWorkbook workbook = new XSSFWorkbook(fis);
			XSSFSheet spreadsheet = workbook.getSheetAt(0);
			Iterator<Row> rowIterator = spreadsheet.iterator();
			while (rowIterator.hasNext()) {
				if (!enough) {
					rowxlsx = (XSSFRow) rowIterator.next();
					// Iterator<Cell> cellIterator = rowxlsx.cellIterator();
					Cell cell = rowxlsx.getCell(0);
					// Cell cell = cellIterator.next();

					switch (cell.getCellType()) {
					case Cell.CELL_TYPE_NUMERIC:
						System.out.print(cell.getNumericCellValue() + " \t\t ");
						break;
					case Cell.CELL_TYPE_BLANK:
						if (cell.getStringCellValue().equals("")) {
							rowList.add(rowxlsx.getRowNum());
						}
						break;
					case Cell.CELL_TYPE_STRING:
						// if (cell.getStringCellValue().contains("SIC Focus
						// Group")
						// || cell.getStringCellValue().contains("Member Type"))
						// {
						currentRow = rowxlsx;
						enough = true;
						// }
						break;
					}
					// System.out.println();
				} else {
					break;
				}
			}
			// LOG.info("rows to delete: " + rowList);
			workbook = null;
			fis.close();
			if (fis != null) {
				fis = null;
				file = null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static HttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLSv1.2");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			// base.getConnectionManager().getSchemeRegistry().register(new
			// Scheme("https", 443, ssf));
			// ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			return new DefaultHttpClient(ccm, base.getParams());
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public static void downLoadImage(HttpClient httpclient, HttpContext localContext, String url, String filepath,
			String imagename) throws Exception {

		HttpGet httpget = new HttpGet(url);
		try {
			String filename = filepath + File.separator + imagename;
			// LOG.info("Downloading image: " + filename);
			// HttpGet httpget = new HttpGet(url);
			httpget.addHeader("Host", "supplier.rt-mart.com.cn");
			httpget.addHeader("Connection", "keep-alive");
			httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0");
			HttpResponse response = httpclient.execute(httpget, localContext);
			int rspStatus = response.getStatusLine().getStatusCode();
			// LOG.info("status " + rspStatus);
			if (rspStatus == HttpStatus.SC_OK) {
				// LOG.info("response status is ok");
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					// LOG.info("entity not null");
					File filePath = new File(filepath);
					if (!(filePath.exists())) {
						// LOG.info("path does not exist creating directory" +
						// filePath.getCanonicalPath());
						filePath.mkdirs();
					}
					File file = new File(filename);
					// LOG.info("image path: " + file.getCanonicalPath());
					if (!(file.exists())) {
						// LOG.info(file.getCanonicalPath() + " does not exist,
						// downloading image");
						FileOutputStream fos = null;
						try {
							// LOG.info(file.getCanonicalPath() + " download
							// start....");
							fos = new FileOutputStream(filename);
							entity.writeTo(fos);
							// LOG.info(file.getCanonicalPath() + " download
							// finish!...");
						} catch (Exception e) {
							// LOG.error("download verification image " +
							// filename, e.fillInStackTrace());
							EntityUtils.consume(entity);
							throw e;
						} finally {
							if (null != fos) {
								fos.flush();
								fos.close();
							}
						}
					} else {
						// LOG.info("local image file exist: " + filepath);
					}
					EntityUtils.consume(entity);
				}
			}
		} catch (Exception e) {
			// LOG.error("download image failed.", e.fillInStackTrace());
			e.printStackTrace();
			/* throw e; */
		} finally {
			httpget.abort();
		}
	}

	public static void deleteFolder(String filepath) {
		if (filepath == null)
			return;
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						deleteFolder(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();
				}
			}
		}
	}

	public static void createFolder(String path) {
		File fnewpath = new File(path);
		// 判断文件夹是否存在
		if (!fnewpath.exists())
			fnewpath.mkdirs();
	}

	public static Date getDate(int dataLag) {
		return DateUtil.getDateAfter(new Date(), -dataLag);
	}

	public static CloseableHttpClient createHttpClient(int timeout) {

		try {

			// 4.3版本超时设置
			RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
					.setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();// 设置请求和传输超时时间
			// RequestConfig globalConfig =
			// RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
			// .setConnectionRequestTimeout(3000).setConnectTimeout(3000).build();
			SSLContextBuilder builder = new SSLContextBuilder();
			builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
			// CloseableHttpClient httpclient =
			// HttpClients.custom().setSSLSocketFactory(sslsf).build();

			// 代理
			// HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
			// DefaultProxyRoutePlanner routePlanner = new
			// DefaultProxyRoutePlanner(proxy);

			CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
					// .setRoutePlanner(routePlanner)
					.setSSLSocketFactory(sslsf).build();

			// 4.X版本的超时设置(4.3后已过时)
			// CloseableHttpClient httpClient = HttpClients.createDefault();
			// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
			// 10000);
			// httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
			// 10000);
			return httpClient;
		} catch (Exception e) {
			// LOG.error("Error", e);
			return null;
		}
	}

	public static Date getDate(int yearsLag, int monthsLag, int daysLag) {
		return DateUtil.getDateAfter(yearsLag, monthsLag, daysLag);
	}

	/**
	 * Generate getter for the attribute
	 * 
	 * @param declaringClass
	 * @param fieldName
	 * @param fieldClass
	 * @return
	 * @throws CannotCompileException
	 */
	public static CtMethod generateGetter(CtClass declaringClass, String fieldName, Class fieldClass)
			throws CannotCompileException {

		String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

		StringBuffer sb = new StringBuffer();
		sb.append("public ").append(fieldClass.getName()).append(" ").append(getterName).append("(){")
				.append("return this.").append(fieldName).append(";").append("}");
		return CtMethod.make(sb.toString(), declaringClass);
	}

	/**
	 * Generate getter Name for the attribute
	 * 
	 * @param fieldName
	 * @return
	 */
	public static String generateGetterName(String fieldName) {

		String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
		return getterName;
	}

	/**
	 * Generate setter for the attribute
	 * 
	 * @param declaringClass
	 * @param fieldName
	 * @param fieldClass
	 * @return
	 * @throws CannotCompileException
	 */
	public static CtMethod generateSetter(CtClass declaringClass, String fieldName, Class fieldClass)
			throws CannotCompileException {

		String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

		StringBuffer sb = new StringBuffer();
		sb.append("public void ").append(setterName).append("(").append(fieldClass.getName()).append(" ")
				.append(fieldName).append(")").append("{").append("this.").append(fieldName).append("=")
				.append(fieldName).append(";").append("}");
		return CtMethod.make(sb.toString(), declaringClass);
	}

	/**
	 * Generate setter Name for the attribute
	 * 
	 * @param fieldName
	 * @return
	 */
	public static String generateSetterName(String fieldName) {

		String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

		return setterName;
	}
	
	
	
}
